﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace CannedHeater.View.Converters
{
    /// <summary>
    /// Converts a number (count) into a Visibility Enum.
    /// Thus able to hide controls if count is 0, and show them otherwise (or opposite way around)
    /// </summary>
    public class NumberToVisibilityConverter : IValueConverter
    {
        // Use default (set by parameter) if num == 0, otherwise uses not(default)
        /// <summary>
        /// Converts a number (count) into a Visibility Enum.
        /// </summary>
        /// <param name="value">Integer count</param>
        /// <param name="targetType">Unused</param>
        /// <param name="parameter">
        /// Boolean ("Show by default").
        /// If true, a count of 0 will return <see cref="Visibility.Visible"/>.
        /// If false, a count of 0 will return <see cref="Visibility.Collapsed"/>
        /// </param>
        /// <param name="culture">Unused</param>
        /// <returns>Visibility enum (Collapsed or Visible)</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Visibility defaultVisibility = (((string) parameter) == "true") ? Visibility.Visible : Visibility.Collapsed;
            if (value == null)
            {
                return defaultVisibility;
            }
            else
            {
                int num = (int) value;
                if (num == 0) return defaultVisibility;
                else return not(defaultVisibility);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null; // Not needed
        }

        /// <summary>
        /// Negates visibility (Visible/Collapsed)
        /// </summary>
        /// <param name="v">Old visibility</param>
        /// <returns>Negated visibility</returns>
        private Visibility not(Visibility v)
        {
            if (v == Visibility.Collapsed) return Visibility.Visible;
            else return Visibility.Collapsed;
        }
    }
}
